import django_filters
from django_filters.rest_framework import DjangoFilterBackend, filters
from rest_framework import status, viewsets
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import mixins
from rest_framework import generics

from DRFApis.filters import UserAddressFilter
from DRFApis.models import UserProfile, UserAddress
from DRFApis.serializers import UserSerializer, UserAddressSerializer


class UserList(APIView):
    """
    User List API
    """
    def get(self, request, format=None):
        users = UserProfile.objects.all()
        users_serializer = UserSerializer(users, many=True)
        return Response(users_serializer.data)

    def post(self, request, format=None):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserAddressList(APIView):
    """
    User Address API
    """
    def get(self, request, format=None):
        address = UserAddress.objects.all()
        address_serializer = UserAddressSerializer(address, many=True)
        return Response(address_serializer.data)


class UserListWithMixin(mixins.ListModelMixin, generics.GenericAPIView):
    """
    使用 Mixin
    """
    # queryset 和 serializer_class 为指定的变量
    queryset = UserAddress.objects.all()
    serializer_class = UserAddressSerializer

    def get(self, request, *args, **kwargs):
        return self.list(self, request, *args, **kwargs)


class StandardResultsSetPagination(PageNumberPagination):
    """
    自定义分页参数
    """
    page_size = 5
    page_size_query_param = 'page_size'
    # ？p=2
    page_query_param = 'p'
    max_page_size = 100


class UserListWithMixin2(generics.ListAPIView):
    """
    使用 Mixin，上一个的更精简的版本
    """
    # queryset 和 serializer_class 为指定的变量
    pagination_class = StandardResultsSetPagination
    queryset = UserAddress.objects.all()
    serializer_class = UserAddressSerializer


class UserAddressListWithViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    使用 ViewSet
    """
    pagination_class = StandardResultsSetPagination
    queryset = UserAddress.objects.all()
    serializer_class = UserAddressSerializer
    # filter_backends = [DjangoFilterBackend]
    # # filterset_fields = ['^province', '^city']
    # filter_class = UserAddressFilter

    filter_backends = [SearchFilter]
    search_fields = ['^province']











